using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseRead.API.Applications.Commands.Hospitals;
using ContentmanagementBaseRead.API.Dtos;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace ContentmanagementBaseRead.API.Applications.Commandhandlters.Hospitals
{
    /// <summary>
    /// 获取医院列表信息命令处理
    /// </summary>
    public class GetHospitalListCommandHandler : IRequestHandler<GetHospitalListCommand, ApiPaging<List<HospitalListDto>>>
    {
        /// <summary>
        /// 医院仓储
        /// </summary>
        private readonly IBaseRepository<HospitalManagementModel> _hospitalRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<GetHospitalListCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="hospitalRepository">医院仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetHospitalListCommandHandler(
            IBaseRepository<HospitalManagementModel> hospitalRepository,
            IMapper mapper,
            ILogger<GetHospitalListCommandHandler> logger)
        {
            _hospitalRepository = hospitalRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取医院列表信息命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public async Task<ApiPaging<List<HospitalListDto>>> Handle(GetHospitalListCommand request, CancellationToken cancellationToken)
        {

            try
            {
                _logger.LogInformation("开始获取医院列表信息，参数：PageIndex={PageIndex}, PageSize={PageSize}", 
                    request.PageIndex, request.PageSize);

                // 获取所有医院数据
                var query = _hospitalRepository.GetAll().AsNoTracking();

                // 应用搜索条件
                if (!string.IsNullOrEmpty(request.HospitalName))
                {
                    query = query.Where(x => x.HospitalName.Contains(request.HospitalName));
                    _logger.LogDebug("应用医院名称搜索条件：{HospitalName}", request.HospitalName);
                }

                if (request.HospitalGrade.HasValue)
                {
                    query = query.Where(x => x.HospitalGrade == request.HospitalGrade.Value);
                    _logger.LogDebug("应用医院等级搜索条件：{HospitalGrade}", request.HospitalGrade.Value);
                }

                if (request.HospitalType.HasValue)
                {
                    query = query.Where(x => x.HospitalType == request.HospitalType.Value);
                    _logger.LogDebug("应用医院类型搜索条件：{HospitalType}", request.HospitalType.Value);
                }

                if (!string.IsNullOrEmpty(request.InTheArea))
                {
                    query = query.Where(x => x.InTheArea.Contains(request.InTheArea));
                    _logger.LogDebug("应用所在区域搜索条件：{InTheArea}", request.InTheArea);
                }

                // 按创建时间倒序排列
                query = query.OrderByDescending(x => x.CreatedTime);

                // 获取总数量
                var totalCount = await query.CountAsync(cancellationToken);
                
                // 计算分页信息
                var pageCount = (int)Math.Ceiling((double)totalCount / request.PageSize);
                var skip = (request.PageIndex - 1) * request.PageSize;

                // 获取分页数据
                var pagedData = await query.Skip(skip).Take(request.PageSize).ToListAsync(cancellationToken);

                // 映射到DTO
                var hospitalListDtos = _mapper.Map<List<HospitalListDto>>(pagedData);

                _logger.LogInformation("医院列表信息获取成功，共获取到 {Count} 个医院，总数量：{TotalCount}", 
                    hospitalListDtos.Count, totalCount);

                return new ApiPaging<List<HospitalListDto>>
                {
                    code = ResultEnumCode.Ok,
                    message = "医院列表信息获取成功",
                    data = hospitalListDtos,
                    TotalCount = totalCount,
                    PageCount = pageCount
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取医院列表信息过程中发生异常");
                return new ApiPaging<List<HospitalListDto>>
                {
                    code = ResultEnumCode.fails,
                    message = $"获取医院列表信息失败：{ex.Message}",
                    data = new List<HospitalListDto>(),
                    TotalCount = 0,
                    PageCount = 0
                };
            }
        }
    }
} 